package com.yenlien.traceyun.business.service;

import com.yenlien.traceyun.business.dao.FeedbackDao;
import com.yenlien.traceyun.business.entity.Feedback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiuSha on 2020/7/24.
 */
@Service
public class FeedbackService {
    @Autowired
    private FeedbackDao feedbackDao;

    public Page<Feedback> findByList(final Feedback feedback) {
        Pageable pageable = PageRequest.of(feedback.getPage(), feedback.getPageSize(), Sort.Direction.DESC, "createtime");
        return feedbackDao.findAll(new Specification<Feedback>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Feedback> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> companyId = root.get("companyId");
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                if (!StringUtils.isEmpty(feedback.getCompanyId())) {
                    list.add(cb.equal(companyId, feedback.getCompanyId()));
                }
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        }, pageable);
    }


    public void save(Feedback feedback) {
        feedbackDao.save(feedback);
    }

    public void update(Feedback feedback) {
        feedbackDao.save(feedback);
    }

    public Feedback findById(String id) {
        return feedbackDao.findById(id);
    }

    public void delete(String id) {
        feedbackDao.deleteById(id);
    }

}
